<template>
  <div class="class-manage">
    <!-- 创建班级部分 -->
    <div class="create-class">
      <h2 style="text-align: center;">班级创建</h2>
      <el-form @submit.prevent="createClass">
        <el-row :gutter="20" type="flex" justify="end">
          <el-col :span="6">
            <el-select v-model="selectedCollege" placeholder="请选择学院">
              <el-option v-for="college in colleges" :key="college.id" :label="college.name" :value="college.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="selectedYear" placeholder="请选择年级">
              <el-option v-for="year in years" :key="year" :label="`${year}入学`" :value="year">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input v-model="className" placeholder="输入班级名称"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="createClass" class="createClass-button">创建班级</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 查询班级部分 -->
    <div class="search-class">
      <h2 style="text-align: center; margin-top: 30px">班级查询</h2>
      <el-form @submit.prevent="searchClasses">
        <el-row :gutter="20" type="flex" justify="end">
          <el-col :span="6">
            <el-select v-model="searchSelectedCollege" placeholder="请选择学院">
              <el-option v-for="college in colleges" :key="college.id" :label="college.name" :value="college.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchSelectedYear" placeholder="请选择年级">
              <el-option v-for="year in years" :key="year" :label="`${year}入学`" :value="year">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <!-- 这里可以添加其他查询条件 -->
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchClasses" class="createClass-button">查询班级</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 查询结果部分 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <h3>查询结果</h3>
      <table>
        <thead>
          <tr>
            <th>班级名称</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="classItem in sortedResults" :key="classItem.id">
            <td>{{ classItem.name }}</td>
            <td>
              <el-button type="danger" size="small" @click="deleteClass(classItem.id)">删除</el-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-else class="no-data-container">
      <p>暂无数据</p>
    </div>
  </div>
</template>

<!-- 脚本和样式保持不变 -->

<script>
import { ref, onMounted, computed } from 'vue';
import { fetchColleges, fetchClasses } from '@/api/api';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'ClassManage',
  setup() {
    const colleges = ref([]);
    const selectedCollege = ref('');
    const searchSelectedCollege = ref('');
    const years = ref(Array.from({ length: new Date().getFullYear() - 1900 }, (_, i) => new Date().getFullYear() - i));
    const className = ref('');
    const selectedYear = ref('');
    const searchSelectedYear = ref('');
    const searchResults = ref([]);
    const sortOrder = ref('asc');

    onMounted(async () => {
      try {
        const data = await fetchColleges();
        colleges.value = data;
      } catch (error) {
        console.error('获取学院列表失败:', error);
      }
    });

    const validateForm = () => {
      if (!searchSelectedCollege.value || !searchSelectedYear.value) {
        ElMessage.error('请选择学院和年级');
        return false;
      }
      return true;
    };

    const createClass = () => {
      if (!className.value) {
        ElMessage.error('请输入班级名称');
      }
      else {
        axios.post('/api/v1/class/create', {
          name: className.value,
          grade: selectedYear.value,
          college_id: selectedCollege.value,
        })
          .then(response => {
            console.log('班级创建成功', response);
            ElMessage.success('班级创建成功');
            searchClasses(); // 创建成功后重新查询班级列表
          })
          .catch(error => {
            console.error('创建班级失败:', error);
            ElMessage.error('班级创建失败');
          });
      }
    };

    const searchClasses = () => {
      if (!validateForm()) return;
      fetchClasses(searchSelectedYear.value, searchSelectedCollege.value)
        .then(classes => {
          searchResults.value = classes;
          sortResults(); // 立即排序结果
          console.log(searchResults.value);
        })
        .catch(error => {
          console.error('查询班级失败:', error);
          ElMessage.error('查询班级失败');
        });
    };

    const deleteClass = (classId) => {
      axios.post('/api/v1/class/delete', {
        id: classId
      })
        .then(response => {
          console.log('删除操作的响应:', response);
          if (response.data.code !== 200) {
            ElMessage.error('删除班级失败: ' + response.data.msg);
          } else {
            ElMessage.success('班级删除成功');
            searchClasses(); // 删除成功后重新查询班级列表
          }
        })
        .catch(error => {
          console.error('删除班级失败:', error);
          ElMessage.error('删除班级失败');
        });
    };

    // 排序函数
    const sortResults = () => {
      searchResults.value.sort(((a, b) => {
        const extractNumber = (str) => {
          const match = str.match(/(\d+)/);
          return match ? parseInt(match, 10) : Number(str);
        };
        const numA = extractNumber(a.name);
        const numB = extractNumber(b.name);
        const textA = a.name.replace(/\d+/g, '');
        const textB = b.name.replace(/\d+/g, '');
        if (textA.localeCompare(textB) !== 0) {
          return textA.localeCompare(textB);
        }
        return numA - numB;
      }));
    };

    // 计算属性，始终返回排序后的结果
    const sortedResults = computed(() => searchResults.value);

    return {
      colleges,
      selectedCollege,
      searchSelectedCollege,
      years,
      selectedYear,
      searchSelectedYear,
      className,
      createClass,
      searchClasses,
      searchResults,
      deleteClass,
      sortOrder,
      sortedResults,
    };
  },
};
</script>

<style>
.class-manage {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

.create-class,
.search-class {
  margin-bottom: 40px;
}

h2 {
  color: #333;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 30px;
}

.el-button {
  padding: 10px 20px;
  font-size: 16px;
}

.search-results {
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-results h3 {
  color: #333;
  border-bottom: 2px solid #ccc;
  padding-bottom: 10px;
  margin-bottom: 0;
}

.search-results table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.search-results th,
.search-results td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.search-results th {
  background-color: #f9f9f9;
  font-weight: bold;
}

.search-results tr:nth-child(even) {
  background-color: #f2f2f2;
}

.search-results tr:hover {
  background-color: #e9e9e9;
}
.no-data-container {
  text-align: center;
  margin-top: 20px;
  color: #666;
}
</style>